package main

import (
	"fmt"
	"gitee.com/hufengjiu/go-zinx/ziface"
	"gitee.com/hufengjiu/go-zinx/znet"
	"log"
)

type PingRouter struct {
	znet.Router
}

func (router *PingRouter) PreHandle(r ziface.IRequest) {
	log.Printf("Call Router Pre %s", r.GetData())
	err := r.GetConnection().SendHasBuf(200, []byte("before ping ... \n"))
	if err != nil {
		log.Println("pre ping error", err)
	}
}

func (router *PingRouter) Handle(r ziface.IRequest) {
	log.Printf("Call Router ing %s", r.GetData())
	err := r.GetConnection().SendHasBuf(200, []byte("ping ping ... \n"))
	err = r.GetConnection().SendHasBuf(200, []byte(fmt.Sprintf("echo %s..", r.GetData())))
	if err != nil {
		log.Println("ing ping error", err)
	}
}

type HelloRouter struct {
	znet.Router
}

func (router *HelloRouter) PreHandle(r ziface.IRequest) {
	log.Printf("----------> Call Router Pre %s", r.GetData())
	err := r.GetConnection().Send(200, []byte("before hello ----------> ... \n"))
	if err != nil {
		log.Println("pre hello ----------> error", err)
	}
}

func (router *HelloRouter) Handle(r ziface.IRequest) {
	log.Printf("Call Router ing %s", r.GetData())
	err := r.GetConnection().Send(200, []byte("hello ----------> hello ----------> ... \n"))
	err = r.GetConnection().Send(200, []byte(fmt.Sprintf("echo %s..", r.GetData())))
	if err != nil {
		log.Println("ing hello ----------> error", err)
	}
}

func ConnectStartCallback(conn ziface.IConnection) {
	log.Println("**********conn start is Called********")
}

func ConnectStopCallback(conn ziface.IConnection) {
	log.Println("**********conn stop is Called********")
}

func main() {
	s := znet.NewServer("zinxV3", "0.0.0.0", 9999)

	s.SetOnConnStart(ConnectStartCallback)
	s.SetOnConnStop(ConnectStopCallback)
	s.AddRouter(1, &PingRouter{})
	s.AddRouter(2, &HelloRouter{})
	s.Serve()
}
